package com.itheima.aop;


import com.itheima.doman.pojo.OperateLog;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 员工日志切面类d
 */

//@Aspect
//@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    // 环绕通知
    @Around("@annotation(com.itheima.anno.Log)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 构建日志对象
        OperateLog operateLog = new OperateLog();
        // 执行方法
        Object result;
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        try {
            result = joinPoint.proceed();
            operateLog.setReturnValue(result != null ? result.toString() : "");
        } finally {
            // 当前时间
            long endTime = System.currentTimeMillis();
            // 耗时
            long costTime = endTime - startTime;
            // 获取当前用户ID
            Integer currentId = CurrentHolder.getCurrentId();
            // 获取当前用户名
            String currentName = CurrentHolder.getCurrentName();
            operateLog.setOperateEmpId(currentId != null ? currentId : 0);
            operateLog.setOperateTime(LocalDateTime.now());
            operateLog.setClassName(joinPoint.getTarget().getClass().getName());
            operateLog.setMethodName(joinPoint.getSignature().getName());
            operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
            operateLog.setCostTime(costTime);
            operateLog.setOperateEmpName(currentName != null ? currentName : "异常登录");
            // 插入日志
            operateLogMapper.insert(operateLog);
        }
        return result;
    }

}
